package servlets.chatting;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.fasterxml.jackson.core.JsonEncoding;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.moma.chatting.core.Message;
import com.moma.chatting.core.ChattingManager;
import com.moma.chatting.core.User;

public class MessagePush extends HttpServlet {
	private ChattingManager mgr = null;
	private JsonGenerator jsonGenerator = null;
	private ObjectMapper objectMapper2 = null;
	
	@Override
	public void init(){
		mgr = ChattingManager.getInstance();
		mgr.initialize();
		
		objectMapper2 = new ObjectMapper();
		
		try {
            jsonGenerator = objectMapper2.getFactory().createGenerator(System.out, JsonEncoding.UTF8);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
	@Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
		doPost(request, response);
		
	}
	@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
		// http://messaging.com/messagePush?id=abc&name=def&msg=ghi&conversationId=1;
		PrintWriter out = response.getWriter();
		
		String userFriendlyName = request.getParameter("name");
		String userUniqueName = request.getParameter("id");
		String msgContent = request.getParameter("msg");
		String conversationIdText = request.getParameter("conversationId");
		int conversationId = 0;
		if (conversationIdText != null && conversationIdText != ""){
			conversationId = Integer.valueOf(conversationIdText);
		}
//		String userFriendlyName = "TestUser1";
//		String userUniqueName = "TestUser_id_01";
//		String msg = "[Servlet] - This is a test message!";
		User fromUser = new User();
		fromUser.setFriendlyName(userFriendlyName);
		fromUser.setUniqueName(userUniqueName);
		
		
		Message msg = new Message();
		msg.setConversationId(conversationId);
		msg.setSender(fromUser);
		msg.setSentWhen(new Date());
		msg.setContent(msgContent);
		
		mgr.pushMessage(msg);
		String debugInfo = objectMapper2.writeValueAsString(msg);
		out.println(debugInfo);
//		String sabc = objectMapper.writeValueAsString(msg);
//		out.println(sabc);
		//out.println("hahaha");
		
//		response.setContentType("text/html;charset=gb2312");
//        PrintWriter out = response.getWriter();
//        request.setCharacterEncoding("gb2312");
//		String userUniqueName = request.getParameter("userUniqueName");
//		String sabc = objectMapper.writeValueAsString(userUniqueName);
//		String tabc = "ABC";
//		out.println(tabc);
		//ObjectMapper mapper = new ObjectMapper();
	}
}

